001 /* 002 * Copyright 2004-2005 Mort Bay Consulting Pty. Ltd. 003 * Copyright 2006 Stephen McConnell. 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 018 package net.dpml.test.http; 019 020 import java.io.IOException; 021 022 import javax.servlet.Filter; 023 import javax.servlet.FilterChain; 024 import javax.servlet.FilterConfig; 025 import javax.servlet.ServletContext; 026 import javax.servlet.ServletException; 027 import javax.servlet.ServletRequest; 028 import javax.servlet.ServletResponse; 029 030 /** 031 * TestFilter. 032 * @author gregw 033 */ 034 public class TestFilter implements Filter 035 { 036 private ServletContext m_context; 037 038 /** 039 * Filter initialization. 040 * @param filterConfig the filter configuration 041 * @exception ServletException if a servlet error occurs 042 */ 043 public void init( FilterConfig filterConfig ) throws ServletException 044 { 045 m_context = filterConfig.getServletContext(); 046 } 047 048 /** 049 * Process a filter request. 050 * @param request the request 051 * @param response the response 052 * @param chain the filter chain 053 * @exception IOException if an I/O error occurs 054 * @exception ServletException if a servlet error occurs 055 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) 056 */ 057 public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) 058 throws IOException, ServletException 059 { 060 Integer oldValue = null; 061 try 062 { 063 oldValue = (Integer) request.getAttribute( "testFilter" ); 064 Integer value = null; 065 if( null == oldValue ) 066 { 067 value = new Integer( 1 ); 068 } 069 else 070 { 071 value = new Integer( oldValue.intValue() + 1 ); 072 } 073 074 request.setAttribute( "testFilter", value ); 075 m_context.setAttribute( "request" + request.hashCode(), value ); 076 chain.doFilter( request, response ); 077 } 078 finally 079 { 080 request.setAttribute( "testFilter", oldValue ); 081 m_context.setAttribute( "request" + request.hashCode(), oldValue ); 082 } 083 } 084 085 /** 086 * Destroy the instance. 087 * @see javax.servlet.Filter#destroy() 088 */ 089 public void destroy() 090 { 091 } 092 093 }